//
//  HJMianTabBar.swift
//  Micro-blog Sina
//
//  Created by admin on 16/3/20.
//  Copyright © 2016年 admin. All rights reserved.
//

import UIKit

class HJMianTabBar: UITabBar {
 /// Attribute---Closure of compose button
    var composeClosure: (() -> Void)?
    
    // Define the total number of tabBar buttons
    private let buttonCount = 5
    override func layoutSubviews() {
        super.layoutSubviews()
        let buttonWidth = bounds.width / CGFloat(buttonCount)
        let frame = CGRect(x: 0, y: 0, width: buttonWidth, height: bounds.height)
        
        var index = 0
        for view in subviews {
            if view is UIControl && !(view is UIButton) {
                view.frame = CGRectOffset(frame, CGFloat(index) * buttonWidth, 0)
                // Set aside the index is 2 position to compose button
                index += index == 1 ? 2 : 1
            }
        }
        // Set the compose button to the middle position
        composeButton.frame = CGRectOffset(frame, 2 * buttonWidth, 0)
    }
    // Click on the compose button
    func composeClick() {
        // Call closure，‘？’ If the closure does not have a value, it is not executed.
        composeClosure?()
    }
    
    // Lazy load compose button(撰写按钮)
    lazy var composeButton: UIButton = {
        let button = UIButton()
        // Add background image
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Normal)
        
        self.addSubview(button)
        button.addTarget(self, action: "composeClick", forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()
}
